package com.bysc.commentservice.aop;

import com.bysc.commentservice.entity.vo.CommentFormVo;
import com.bysc.commentservice.entity.vo.PostFormVo;
import com.bysc.commentservice.entity.vo.SonCommentFormVo;
import com.bysc.commonutils.Results;
import com.github.houbb.sensitive.word.bs.SensitiveWordBs;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashMap;

import static com.bysc.commonutils.constant.RedisConstant.*;

@Aspect
@Component
@Slf4j
public class CommentAop {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SensitiveWordBs sensitiveWordBs;

    @Pointcut("execution(* com.bysc.commentservice.controller.*.add*(..)) && !execution(* com.bysc.commentservice.controller.CommentTypeController.*(..))")
    public void addPointCut() {
    }

    @Pointcut("execution(* com.bysc.commentservice.controller.*.delete*(..)) && !execution(* com.bysc.commentservice.controller.CommentTypeController.*(..))")
    public void deletePointCut() {
    }

    @Pointcut("execution(* com.bysc.commentservice.controller.CommentParentController.getCommentListByTokenAndPostId*(..))")
    public void viewCountPointCut() {
    }

    @Around("viewCountPointCut()")
    public Results viewCountAround(ProceedingJoinPoint joinPoint) throws Throwable {
        // 执行原方法
        Results result = (Results) joinPoint.proceed();

        // 检查方法是否执行成功
        if (result.getSuccess()) {
            Object id = joinPoint.getArgs()[0];
            // 构造Redis的key
            String key = COMMENT_POST + id;
            // 使用RedisTemplate递增浏览量
            redisTemplate.opsForHash().increment(key, _VIEW, 1);
            // 可以选择将新的浏览量写回结果中
        }
        return result;
    }

    @Around("addPointCut()")
    public Results addPointCut(ProceedingJoinPoint joinPoint) throws Throwable {
        // 日志记录
        log.info("调用了方法: {}", joinPoint.getSignature().getName());
       Object[] args = joinPoint.getArgs();
        Object args0 = args[0];
        /* String text = "";
        if (args0 instanceof PostFormVo) {
            text = ((PostFormVo) args0).getContent();
        } else if (args0 instanceof CommentFormVo) {
            text = ((CommentFormVo) args0).getContent();
        } else if (args0 instanceof SonCommentFormVo) {
            text = ((SonCommentFormVo) args0).getContent();
        }
        if (!StringUtils.isEmpty(text)) {
            //敏感词过滤
            text = sensitiveWordBs.replace(text);
            if (args0 instanceof PostFormVo) {
                ((PostFormVo) args0).setContent(text);
            } else if (args0 instanceof CommentFormVo) {
                ((CommentFormVo) args0).setContent(text);
            } else if (args0 instanceof SonCommentFormVo) {
                ((SonCommentFormVo) args0).setContent(text);
            }
        Results result = (Results) joinPoint.proceed(args);

        }*/
        // 获取并执行目标方法
        Results result = (Results) joinPoint.proceed();

        // 处理返回值
        if (result.getSuccess()) {
            Object id = result.getData().get("id");
            if (joinPoint.getSignature() instanceof MethodSignature) {
                initRedis(args0, id);
            }

        }
        return result;
    }

    private void initRedis(Object arg, Object id) {
        String key = "";
        String fileUrl = "";
        HashMap<String, Object> map = new HashMap<>();
        map.put(_LIKE, 0);
        if (arg instanceof PostFormVo) {
            fileUrl = ((PostFormVo) arg).getPostImage();

            key = COMMENT_POST + id;
            map.put(_COLLECT, 0);
            map.put(_VIEW, 0);
        } else if (arg instanceof CommentFormVo) {
            fileUrl = ((CommentFormVo) arg).getContentImage();

            key = COMMENT_PARENTCOMMENT + id;
        } else if (arg instanceof SonCommentFormVo) {
            fileUrl = ((SonCommentFormVo) arg).getContentImage();

            key = COMMENT_SONCOMMENT + id;
        }
        if (!StringUtils.isEmpty(fileUrl)) {
            redisTemplate.opsForSet().add(FILE_URL_DB_RESOURCES, fileUrl); // 图片地址缓存
        }
        if (!StringUtils.isEmpty(key)) {
            redisTemplate.opsForHash().putAll(key, map); //帖子，评论信息初始化缓存
        }
    }


    @Around("deletePointCut()")
    public Results deletePointCut(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取并执行目标方法
        Results result = (Results) joinPoint.proceed();

        // 删除对应的 Redis 中的键值对
        if (result.getSuccess()) {
            Object id = result.getData().get("id");
            if (result.getSuccess()) {
                // 获取方法签名
                MethodSignature signature = (MethodSignature) joinPoint.getSignature();
                String methodName = signature.getMethod().getName();
                String key = "";
                // 根据方法名来确定key的前缀
                if (methodName.startsWith("deletePost")) {
                    key = COMMENT_POST + id;
                } else if (methodName.startsWith("deleteParent")) {
                    key = COMMENT_PARENTCOMMENT + id;
                } else if (methodName.startsWith("deleteSon")) {
                    key = COMMENT_SONCOMMENT + id;
                }

                // 如果key不为空，删除Redis中的key
                if (!key.isEmpty()) {
                    redisTemplate.delete(key);
                }
            }
        }
        return result;
    }
}



